package com.ruoyi.web.controller.mbti;

import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MbtiTestRecord;
import com.ruoyi.system.domain.MbtiResult;
import com.ruoyi.system.service.IMbtiTestRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * MBTI测试记录管理Controller
 *
 * @author ruoyi
 * @date 2025-08-22
 */
@RestController
@RequestMapping("/mbti/testRecord")
public class MbtiTestRecordController extends BaseController
{
    @Autowired
    private IMbtiTestRecordService mbtiTestRecordService;

    /**
     * 查询MBTI测试记录列表
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(MbtiTestRecord mbtiTestRecord)
    {
        startPage();
        List<MbtiTestRecord> list = mbtiTestRecordService.selectMbtiTestRecordList(mbtiTestRecord);
        return getDataTable(list);
    }

    /**
     * 导出MBTI测试记录列表
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:export')")
    @Log(title = "MBTI测试记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MbtiTestRecord mbtiTestRecord)
    {
        List<MbtiTestRecord> list = mbtiTestRecordService.selectMbtiTestRecordList(mbtiTestRecord);
        ExcelUtil<MbtiTestRecord> util = new ExcelUtil<MbtiTestRecord>(MbtiTestRecord.class);
        util.exportExcel(response, list, "MBTI测试记录数据");
    }

    /**
     * 获取MBTI测试记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:query')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        return success(mbtiTestRecordService.selectMbtiTestRecordByRecordId(recordId));
    }

    /**
     * 新增MBTI测试记录
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:add')")
    @Log(title = "MBTI测试记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MbtiTestRecord mbtiTestRecord)
    {
        mbtiTestRecord.setCreateBy(getUsername());
        return toAjax(mbtiTestRecordService.insertMbtiTestRecord(mbtiTestRecord));
    }

    /**
     * 修改MBTI测试记录
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:edit')")
    @Log(title = "MBTI测试记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MbtiTestRecord mbtiTestRecord)
    {
        mbtiTestRecord.setUpdateBy(getUsername());
        return toAjax(mbtiTestRecordService.updateMbtiTestRecord(mbtiTestRecord));
    }

    /**
     * 删除MBTI测试记录
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:remove')")
    @Log(title = "MBTI测试记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(mbtiTestRecordService.deleteMbtiTestRecordByRecordIds(recordIds));
    }

    /**
     * 获取测试记录统计信息
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics(@RequestParam(required = false) String startDate,
                                   @RequestParam(required = false) String endDate)
    {
        Map<String, Object> statistics = mbtiTestRecordService.getTestRecordStatistics(startDate, endDate);
        return success(statistics);
    }

    /**
     * 获取测试记录详情（包含答题记录和结果）
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:detail')")
    @GetMapping("/detail/{recordId}")
    public AjaxResult getTestRecordDetail(@PathVariable Long recordId)
    {
        try {
            Map<String, Object> detail = mbtiTestRecordService.getTestRecordDetail(recordId);
            return success(detail);
        } catch (Exception e) {
            return error("获取测试记录详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的测试历史
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:history')")
    @GetMapping("/history/{userId}")
    public TableDataInfo getUserTestHistory(@PathVariable Long userId)
    {
        startPage();
        List<MbtiTestRecord> list = mbtiTestRecordService.selectTestRecordsByUserId(userId);
        return getDataTable(list);
    }

    /**
     * 批量更新测试记录状态
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:edit')")
    @Log(title = "批量更新测试记录状态", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdateStatus")
    public AjaxResult batchUpdateStatus(@RequestParam Long[] recordIds, @RequestParam String status)
    {
        try {
            int count = mbtiTestRecordService.batchUpdateStatus(recordIds, status, getUsername());
            return success("成功更新 " + count + " 条记录状态");
        } catch (Exception e) {
            return error("批量更新状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取测试完成度统计
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:statistics')")
    @GetMapping("/completionStats")
    public AjaxResult getCompletionStats()
    {
        Map<String, Object> stats = mbtiTestRecordService.getCompletionStatistics();
        return success(stats);
    }

    /**
     * 获取人格类型分布统计
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:statistics')")
    @GetMapping("/personalityDistribution")
    public AjaxResult getPersonalityDistribution(@RequestParam(required = false) String startDate,
                                                @RequestParam(required = false) String endDate)
    {
        Map<String, Object> distribution = mbtiTestRecordService.getPersonalityDistribution(startDate, endDate);
        return success(distribution);
    }

    /**
     * 重新计算测试结果
     */
    @PreAuthorize("@ss.hasPermi('mbti:testRecord:edit')")
    @Log(title = "重新计算测试结果", businessType = BusinessType.UPDATE)
    @PostMapping("/recalculate/{recordId}")
    public AjaxResult recalculateResult(@PathVariable Long recordId)
    {
        try {
            MbtiResult result = mbtiTestRecordService.recalculateTestResult(recordId);
            return success(result);
        } catch (Exception e) {
            return error("重新计算失败：" + e.getMessage());
        }
    }
}
